package cn.hfjava.kz.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hfjava.kz.common.CreateGroup;
import cn.hfjava.kz.common.UpdateGroup;
import cn.hfjava.kz.entity.dto.StudentFormDTO;
import cn.hfjava.kz.entity.dto.StudentSavaDTO;
import cn.hfjava.kz.entity.dto.StudentSearchDTO;
import cn.hfjava.kz.entity.excel.StudentExcel;
import cn.hfjava.kz.entity.po.Student;
import cn.hfjava.kz.entity.vo.PageVO;
import cn.hfjava.kz.listener.StudentListener;
import cn.hfjava.kz.mapper.StudentMapper;
import cn.hfjava.kz.service.StudentService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author 29264
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/student")
@Tag(name = "考生管理", description = "考试管理")
public class StudentController {
    private final StudentService studentService;
    private final StudentMapper studentMapper;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

//        @Operation(summary = "分页查询考生")
//        @PostMapping("/queryStudent")
//        public SaResult listPage(@RequestBody StudentQueryDTO studentQueryDTO) {
//            // 使用Lambda表达式【指定需要查询的字段】
//            IPage<Student> page = new Page<>(studentQueryDTO.getCurPage(), studentQueryDTO.getPageSize());
//
//            // 设置查询条件
//            QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
//
//            // 考生姓名
//            if (StringUtils.isNotBlank(studentQueryDTO.getName())) {
//                queryWrapper.lambda().like(Student::getName, studentQueryDTO.getName());
//            }
//
//            // 手机号
//            if (StringUtils.isNotBlank(studentQueryDTO.getPhone())) {
//                queryWrapper.lambda().like(Student::getPhone, studentQueryDTO.getPhone());
//            }
//
//            // 身份证号
//            if (StringUtils.isNotBlank(studentQueryDTO.getIdNum())) {
//                queryWrapper.lambda().like(Student::getIdentityId, studentQueryDTO.getIdNum());
//            }
//
//            // 申报状态
//            if (studentQueryDTO.getStatus() != null) {
//                queryWrapper.lambda().eq(Student::getStatus, studentQueryDTO.getStatus());
//            }
//
//            // 考生来源
//            if (studentQueryDTO.getSource() != null) {
//                queryWrapper.lambda().eq(Student::getSource, studentQueryDTO.getSource());
//            }
//
//            // 招生老师
//            if (StringUtils.isNotBlank(studentQueryDTO.getTeacher())) {
//                queryWrapper.lambda().eq(Student::getTeacher, studentQueryDTO.getTeacher());
//            }
//
//            // 排除字段查询
//            queryWrapper.select(Student.class, info -> !info.getColumn().equals("deleted")
//                    && !info.getColumn().equals("userId"));
//
//            // 查询
//            IPage<Student> pageResult = studentService.page(page, queryWrapper);
//
//            // 封装，返回
//            PageVO pageVo = new PageVO<>();
//            pageVo.setTotal(pageResult.getTotal());
//            pageVo.setList(pageResult.getRecords());
//            pageVo.setPageSize(pageResult.getSize());
//            pageVo.setCurrentPage(pageResult.getCurrent());
//
//            return SaResult.ok().setData(pageVo);
//
//    }



//    @PostMapping("/save")
//    @Operation(summary = "保存考生信息")
//    public SaResult save(@RequestBody @Validated(value = { CreateGroup.class }) StudentSavaDTO student){
//        Student studentPo = new Student();
//        BeanUtils.copyProperties(student,studentPo);
//        String passwordHash = bCryptPasswordEncoder.encode(studentPo.getPassword());
//        studentPo.setPassword(passwordHash);
//        // 获取扩展参数
//        String name = StpUtil.getExtra("username").toString();
//        int userId = StpUtil.getLoginIdAsInt();
//        // avatar    /uploads/images/2024/07/19/王磊/wangLei.jpg
//        studentPo.setCreatedBy(name); // 创建人
//        studentPo.setUserId(userId); // 创建人ID
//        studentPo.setCreatedDate(LocalDateTime.now()); // 创建时间
//        studentPo.setDeleted(0); // 逻辑删除标识 0表示未删除  1表示已删除
//        studentPo.setStatus(0);  // 审报状态 0表示待审报  1表示已审报（当生成《职业技能等级认定个人申报审核表》更新为此状态）
//        studentService.save(studentPo); // 添加考生信息
//        return SaResult.ok("保存考生信息成功");
//    }



    @PostMapping("/save")
    @Operation(summary = "保存考生信息")
    public SaResult save(@RequestBody @Validated(value = { CreateGroup.class }) StudentSavaDTO student){

        String passwordHash = bCryptPasswordEncoder.encode(student.getPassword());
        student.setPassword(passwordHash);
        // 获取扩展参数
        String name = StpUtil.getExtra("username").toString();
        int userId = StpUtil.getLoginIdAsInt();
        studentService.saveStuAllInfo(student, name, userId); // 添加考生信息
        return SaResult.ok("保存考生信息成功");
    }

//        studentPo.setCreatedBy(name); // 创建人
//        studentPo.setUserId(userId); // 创建人ID
//        studentPo.setCreatedDate(LocalDateTime.now()); // 创建时间
//        studentPo.setDeleted(0); // 逻辑删除标识 0表示未删除  1表示已删除
//        studentPo.setStatus(0);  // 审报状态 0表示待审报  1表示已审报（当生成《职业技能等级认定个人申报审核表》更新为此状态）




    @PutMapping("/update")
    @Operation(summary = "修改考生信息")
    public SaResult update(@RequestBody @Validated(value = { UpdateGroup.class }) StudentFormDTO student){
        Student studentPo = new Student();
        BeanUtils.copyProperties(student,studentPo);
        studentService.updateById(studentPo);
        return SaResult.ok("修改考生信息成功");
    }

    @GetMapping("/detail")
    @Operation(summary = "查询考生详情")
    public SaResult detail(@RequestParam(value = "id") Integer id){
        Student student = studentService.getById(id);
        if(student == null) {
            return SaResult.error("查询失败，该考生不存在");
        }
        student.setPassword("");
        return SaResult.ok("查询成功").setData(student);
    }
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除考生", description = "根据考生ID删除指定考生")
    public SaResult deleteById(@PathVariable(value = "id",required = true)
                               Integer id) {
        Student stu = studentService.getById(id);
        if(stu == null){
            return SaResult.error("此考生不存在");
        }
        studentService.removeById(id);
        return SaResult.ok("考生删除成功！");
    }



    @PostMapping("/batch-delete")
    @Operation(summary = "批量逻辑删除考生")
    public SaResult batchDelete(@RequestBody Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return SaResult.error("至少需要提供一个考生ID");
        }

        LambdaUpdateWrapper<Student> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Student::getId, ids);
        updateWrapper.set(Student::getDeleted, 1);

        int count = studentMapper.update(null, updateWrapper);

        return SaResult.ok("成功逻辑删除了 " + count + " 个考生");
    }



//    @Operation(summary = "导入excel")
//    @PostMapping(value = "/import", consumes = "multipart/form-data")
//    @ResponseBody
//    public SaResult daoRu(
//            @RequestPart(name = "file", required = true) MultipartFile file,
//            HttpServletResponse response) throws IOException {
//        long t1 = System.currentTimeMillis();
//        int userId = StpUtil.getLoginIdAsInt();
//        String name = String.valueOf(StpUtil.getExtra("username"));
//        System.out.println("从 StpUtil 获取的 username: " + StpUtil.getExtra("username"));
//        System.out.println("当前登录用户ID：" + userId);
//        System.out.println("当前登录用户名：" + name);
//
//
//
//        // 添加 headRowNumber 参数来跳过第一行
//        EasyExcel.read(file.getInputStream(), StudentExcel.class, new StudentListener(studentService, name, userId))
//                .headRowNumber(1) // 设置跳过第一行
//                .sheet()
//                .doRead();
//
//        long t2 = System.currentTimeMillis();
//        return SaResult.ok("导入成功，耗时：" + (t2 - t1) + "ms");
//    }



    @Operation(summary = "导入excel")
    @PostMapping(value = "/import", consumes = "multipart/form-data")
    @ResponseBody
    public SaResult daoRu(
            @RequestPart(name = "file", required = true) MultipartFile file,
            HttpServletResponse response) throws IOException {
        long t1 = System.currentTimeMillis();
        int userId = StpUtil.getLoginIdAsInt();
        String name = String.valueOf(StpUtil.getExtra("username"));
        System.out.println("从 StpUtil 获取的 username: " + StpUtil.getExtra("username"));
        System.out.println("当前登录用户ID：" + userId);
        System.out.println("当前登录用户名：" + name);

        try {
            // 创建 StudentListener
            StudentListener listener = new StudentListener(studentService, name, userId, true);

            // 读取 Excel 文件
            EasyExcel.read(file.getInputStream(), StudentExcel.class, listener)
                    .headRowNumber(1) // 设置跳过第一行
                    .sheet()
                    .doRead();

            // 检查重复数据错误信息
            List<String> errorMessages = listener.getErrorMessages();
            if (!errorMessages.isEmpty()) {
                return SaResult.error("导入失败: " + String.join(", ", errorMessages));
            }

            long t2 = System.currentTimeMillis();
            return SaResult.ok("导入成功，耗时：" + (t2 - t1) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("导入失败，发生异常：" + e.getMessage());
        }
    }
    @Operation(summary = "根据组合条件分页获取考生信息列表")
    @PostMapping("page")
    public SaResult queryPage(@RequestBody StudentSearchDTO stuDto){
        PageVO pageVo = studentService.searchPage(stuDto);
        return SaResult.data(pageVo);
    }




















































    @Operation(summary = "导出所有考生的excel")
    @PostMapping(value = "/exportAll")
    public void exportAll(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("考生表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 从本地模板中读取
        String templatePath = "D:\\kz\\uploadPath\\Templates\\系统申报表.xlsx";
        try (InputStream templateInputStream = new FileInputStream(templatePath)) {
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(templateInputStream)
                    .sheet()
                    .doWrite(studentService.getData());
        }
    }


    @PostMapping("/export")
    @Operation(summary = "根据考生id导出Excel", description = "根据选择考生ID集合来导出考生信息")
    public void export(@RequestBody List<Integer> idList, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("考生信息表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 获取考生数据
        List<StudentExcel> stuDataList = studentService.findStudentExcelByIdList(idList);
        if (stuDataList.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            response.getWriter().write("没有找到相关数据");
            return;
        }

        // 从本地模板中读取
        String templatePath = "D:\\kz\\uploadPath\\Templates\\系统申报表.xlsx";
        try (InputStream templateInputStream = new FileInputStream(templatePath)) {
            // 创建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                    .withTemplate(templateInputStream)
                    .build();

            // 创建写入sheet
            WriteSheet writeSheet = EasyExcel.writerSheet()
                    .build();

            // 写入数据，不包含表头
            excelWriter.write(stuDataList, writeSheet);
            excelWriter.finish();
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("文件生成失败");
        }
    }
}
